import Vue from 'vue'
import store from '../../../store'
let userId = ''
//打开数据库
function openDatabase() {
	userId = JSON.parse(store.getters.userInfo).id
	console.log('打开数据库',userId);
	return new Promise((reslove, reject) => {
		plus.sqlite.openDatabase({
			name: 'chatDB' + userId, //数据库名称
			path: '_doc/' + userId + '/test.db', //数据库路径
			success: function(e) {
				console.log('数据库打开 success!');
				reslove(e)
			},
			fail: function(e) {
				console.log('数据库打开 failed: ' + JSON.stringify(e));
				reject(e)
			}
		});
	})
}
// 判断数据库是否打开
function isOpenDatabase() {
	userId = JSON.parse(store.getters.userInfo).id
	let sulte = plus.sqlite.isOpenDatabase({
		name: 'chatDB' + userId, //数据库名称
		path: '_doc/' + userId + '/test.db', //数据库路径
	});
	// console.log('数据库是否打开' + sulte + 'chatDB' + userId);
	return sulte
}
//关闭数据库
function closeDatabase() {
	userId = JSON.parse(store.getters.userInfo).id
	plus.sqlite.closeDatabase({
		name: 'chatDB' + userId, //数据库名称
		success: function(e) {
			console.log('关闭数据库 success!');
		},
		fail: function(e) {
			console.log('关闭数据库 failed: ' + JSON.stringify(e));
		}
	});
}
//执行增删改等操作的SQL语句
function executeSql(sql) {
	userId = JSON.parse(store.getters.userInfo).id
	transaction('begin')
	return new Promise((reslove, reject) => {
		plus.sqlite.executeSql({
			name: 'chatDB' + userId, //数据库名称
			sql: sql,
			success: function(e) {
				console.log('增删改等操作 success!' + sql+JSON.stringify(e));
				transaction('commit')
				reslove(e)
				
			},
			fail: function(e) {
				console.log('增删改等操作 failed: ' + sql + JSON.stringify(e));
				transaction('rollback')
				reject(e)
			}
		});
	})
}
//开启事务
function transaction(operation) {
	userId = JSON.parse(store.getters.userInfo).id
	return new Promise((reslove, reject) => {
		plus.sqlite.transaction({
			name: 'chatDB' + userId, //数据库名称
			operation: operation,
			success: function(e) {
				console.log('transaction success!');
			},
			fail: function(e) {
				console.log('transaction failed: ' + JSON.stringify(e));
			}
		});
	})
}

//执行查询的SQL语句
function selectSql(sql) {
	userId = JSON.parse(store.getters.userInfo).id
	return new Promise((reslove, reject) => {
		plus.sqlite.selectSql({
			name: 'chatDB' + userId,
			sql: sql,
			success: function(data) {
				console.log('执行查询的SQL语句 success: ' + sql);
				reslove(data)
			},
			fail: function(e) {
				console.log('执行查询的SQL语句 failed: ' + sql + JSON.stringify(e));
				reject(e)
			}
		});
	})
}
//插入数据
async function insertDataFn(msg) {
	/**
	 * type:系统消息【system】用户消息【user】
	 * messageType：消息类型 文本【text】图片【img】音频【voice】视频【Video】红包【redEnvelope】
	 * userId:发送者id 
	 * userInfo发送者用户信息,
	 * receiveId:接收者id
	 * receiveInfo:接收者用户信息, 
	 * content：消息内容
	 * time：发送时间
	 * isSend:0未发送，1已发送
	 * isRead是否已读，0未读，1已读
	 * isTop是否置顶
	 * isMsgShow当前消息在消息列表中是否删除【不显示】默认为显示1  0不显示
	 * secretKey:量子解密需要的secretKey
	 **/
	// console.log(JSON.stringify(msg.content));
	let sql =
		`insert into message (type,userId,userInfo,receiveId,receiveInfo,messageType,content,time,isSend,uuid,isRead,isTop,isMsgShow,secretKey)
	values ("${msg.type}","${msg.userId}",'${msg.userInfo}',"${msg.receiveId}",'${msg.receiveInfo}',"${msg.messageType}",'${JSON.stringify(msg.content)}',"${msg.time}",${msg.isSend},"${msg.uuid}",${msg.isRead},${msg.isTop},${msg.isMsgShow},"${msg.secretKey||''}")`
	return new Promise((reslove, reject) => {
		executeSql(sql).then(res => {
			let req={
				code:'0',
				data:res
			}
			reslove(req)
		}).catch(err => {
			let req={
				code:'400',
				data:err
			}
			reject(req)
		})
	})
}
//分页查询数据
async function getPageLimit(req) {
	userId = JSON.parse(store.getters.userInfo).id
	/**
	 * pageSize:一页多少条
	 * pageNum：当前第几页
	 * **/
	let num = req.pageSize * (req.pageNum-1)
	let sql = `select * from message where (userId = '${userId}' and receiveId = '${req.receiveId}') or (userId ='${req.receiveId}' and receiveId = '${userId}') order by id desc limit ${req.pageSize} offset ${num}`;
	let sql2 = `select count(*) from message where (userId = '${userId}' and receiveId = '${req.receiveId}') or (userId ='${req.receiveId}' and receiveId = '${userId}')`;
	let count = await selectSql(sql2)
	let result = await selectSql(sql)
	// console.log('分页查询数据结果' + JSON.stringify(result));
	// console.log('分页查询总数' + count[0]['count(*)']+sql);
	return new Promise((reslove, reject) => {
		if(result&&count){
			let req={
				code:'0',
				data:result.reverse(),
				count:count[0]['count(*)']
			}
			reslove(req)
		}else{
			let req={
				code:'400',
				msg:'查询出错'
			}
			reject(req)
		}
	})
	return 
}
//更改数据库字段
//uuid当前一条数据的uuid
//name要修改的字段  value要更新值
async function changeSQDataFn(uuid,name,value) {
	let sql=`update message set ${name} = ${value} WHERE uuid = "${uuid}"`
	return new Promise((reslove, reject) => {
		executeSql(sql).then(res => {
			let req={
				code:'0',
				data:res
			}
			reslove(req)
		}).catch(err => {
			let req={
				code:'400',
				data:err
			}
			reject(req)
		})
	})
	
}
//删除聊天记录
async function deleteChatRecord(req) {
	userId = JSON.parse(store.getters.userInfo).id
	/**
	 * userId:当前用户id
	 * receiveId:接收者id
	 **/
	// console.log(JSON.stringify(msg.content));
	let sql =`delete from message where  (userId = '${userId}' and receiveId = '${req.receiveId}') or (userId ='${req.receiveId}' and receiveId = '${userId}')`
	return new Promise((reslove, reject) => {
		executeSql(sql).then(res => {
			let req={
				code:'0',
				data:res
			}
			reslove(req)
		}).catch(err => {
			let req={
				code:'400',
				data:err
			}
			reject(req)
		})
	})
}


//消息列表操作

//查询所有消息列表
async function selectUnreadMsg() {
	userId = JSON.parse(store.getters.userInfo).id
	/**
	 * userId:当前用户id
	 * receiveId:接收者id
	 * isRead:0未读1已读
	 **/
	// console.log(JSON.stringify(msg.content));or userId = '${userId}'
	let sql =`select * from message where receiveId = '${userId}' or userId = '${userId}'`
	let result = await selectSql(sql)
	return new Promise((reslove, reject) => {
		if(result){
			let req={
				code:'0',
				data:result
			}
			reslove(req)
		}else{
			let req={
				code:'400',
				msg:'查询出错'
			}
			reject(req)
		}
	})
}
//更新数据库当前发送者用户，所有未读消息，改为已读
async function updateUnreadMsg(receiveId) {
	userId = JSON.parse(store.getters.userInfo).id
	/**
	 * userId:当前用户id
	 * receiveId:接收者id
	 * isRead:0未读1已读
	 **/
	// console.log(JSON.stringify(msg.content));
	let sql =`update message set isRead = 1 where receiveId = '${userId}' and userId = '${receiveId}'`
	let result = await selectSql(sql)
	return new Promise((reslove, reject) => {
		executeSql(sql).then(res => {
			let req={
				code:'0',
				data:res
			}
			reslove(req)
		}).catch(err => {
			let req={
				code:'400',
				data:err
			}
			reject(req)
		})
	})
}








module.exports = {
	openDatabase,
	isOpenDatabase,
	closeDatabase,
	executeSql,
	selectSql,
	//消息表message
	insertDataFn,//插入数据
	getPageLimit,//分页查询数据
	changeSQDataFn,//更改数据库字段
	deleteChatRecord,//删除聊天记录
	selectUnreadMsg,//查询未读消息列表
	updateUnreadMsg,//更新未读为已读消息
}
